package com.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.XmlBean;
import com.util.Constant;

public class BaseServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("信息： BaseServlet___service...");
		
		//取得 url
		String path = request.getServletPath().split("\\.")[0];
		ServletContext context = this.getServletContext();
		try {
			Object parObj = context.getAttribute(Constant.ANALYTICAL_MAP);
			if(parObj == null){
				System.out.println("-------：没有在上下文中找到解析文件！");
				throw new RuntimeException("没有在上下文中找到解析文件！");
			}
			
			@SuppressWarnings("unchecked")
			Map<String,XmlBean> xmls = (Map<String, XmlBean>) parObj;
			
			XmlBean item = xmls.get(path);
			if(item == null){
				System.out.println("-------：不存在该路径:"+path+"！");
				throw new RuntimeException("不存在该路径:"+path+"！");
			}
			
			
			Class<?> classType = item.getClassType();
			Class<?>[] paramClass = item.getParamClass();
	        Object invokeClass = classType.newInstance();
	        Method runMethod = classType.getMethod(item.getMethodName(), paramClass);
	        
	        /**
	         * 从请求中取得参数
	         * TODO 参数缺陷
	         * 		1.这里没有验证 注解RequestMapping的method类型
	         * 		2.参数类型单一，没有考虑 int等基本类型的情况
	         * 		3.参数没有考虑不加注解的情况
	         */
	        List<String> paramNames = item.getParamNames();
	        Object[] parObjs = new Object[paramNames.size()];
	        for(int i = 0; i < paramNames.size(); i++){
	        	Object param = null;
	        	if( paramNames.get(i) != "" ){
	        		param = request.getParameter(paramNames.get(i));
	        	}
	        	if( param == null ){
	        		param = new Object();
	        	}
	        	parObjs[i] = param;
	        }
	        
	        /**
	         * 执行方法
	         * TODO 方法缺陷
	         * 		方法必须返回字符串(页面)，且没有强制限定
	         */
	        String result = (String) runMethod.invoke(invokeClass, parObjs);
	        
	        request.getRequestDispatcher(result).forward(request, response);
	        
		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			request.getRequestDispatcher("error.jsp").forward(request, response);
		} catch (Exception e) {
			System.out.println("----> Exception error----------------");
			e.printStackTrace();
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}
		
	}

	@Override
	public void destroy() {
		System.out.println("信息：BaseServlet___destroy...");
	}

	@Override
	public void init() throws ServletException {
		System.out.println("信息：BaseServlet___init...");
	}

	
}
